#pragma once
#include "histogram.h"

namespace roto
{
	namespace histogram
	{
		float* get_histogram_array(uchar* Gs, uint width, uint height)
		{
			float* Hv = new float[256];
			for(uint i = 0; i < 256; i++)
				Hv[i] = 0;
			
			for(uint y = 0; y < height; ++ y)
				for(uint x = 0; x < width; ++ x)
					Hv[Gs[y * width + x]] ++;
			return Hv;
		}


		float* histogram_distribution(uchar* Gs, uint width, uint height)
		{
			float* Hv = get_histogram_array(Gs, width, height);
			float all = (float)(width * height);
			for(uint i = 0; i < 256; i++)
				Hv[i] /= all;
			return Hv;
		}

		float* calc_norm_histogram_array(float* Hv)
		{
			float max = 0;
			for(uint i = 0; i < 256; i++)
				if(Hv[i] > max) max = Hv[i];
			for(uint i = 0; i < 256; i++)
				Hv[i] /= max;
			return Hv;
		}

		uchar* histogram_linearization(uchar* Gs, uint width, uint height)
		{
			float n = (float)(width * height);
			
			uchar* Td = new uchar[(uint)n];

			float si;
			float* Hv = get_histogram_array(Gs, width, height);
			
			long xy;
			for(uint y = 0; y < height; ++ y)
				for(uint x = 0; x < width; ++ x)
				{
					si = .0f;
					xy = y * width + x;
					for(uint i = 0; i <= Gs[xy]; i++)
						si += Hv[i];
					Td[xy] = (uint)(si / n * 255.0f);
				}

			return Td;	
		}
	}
}